import { message } from 'ant-design-vue'

/**
 * 获取文件后缀名
 */
export const getFileExtension = (filename) => {
  return filename.split('.').pop().toLowerCase()
}

/**
 * 获取文件名, 除去后缀名
 */
export const getFileNameWithoutExt = (filename) => {
  return filename.substring(0, filename.lastIndexOf('.'))
}
/**
 * @files [Array] 需要验证的文件列表，需要是一个数组
 * @return Boolean
 */
export const isFileNameLengthExceed = (files, maxLength = 100) => {
  if (Object.prototype.toString.call(files) !== '[object Array]') {
    console.error('第一个参数必须是数组!')
    return false
  }
  return files.some((file) => {
    return new Blob([file.name]).size > maxLength
  })
}

export const downloadImage = (url, fileName) => {
  var xhr = new XMLHttpRequest()
  xhr.open('GET', url, true)
  xhr.responseType = 'blob'
  xhr.onload = function (e) {
    if (this.status == 200) {
      var blob = this.response
      var a = document.createElement('a')
      a.href = window.URL.createObjectURL(blob)
      a.download = fileName
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
  xhr.withCredentials = true
  xhr.send()
}
export const getImageWidthHeight = (file) => {
  let promise = new Promise((resolve, reject) => {
    var reader = new FileReader()

    reader.onload = (function (theFile) {
      return function (e) {
        var img = new Image()
        img.src = e.target.result
        img.onload = function () {
          resolve({ width: img.width, height: img.height })
        }
        img.onerror = function () {
          resolve({ width: null, height: null })
        }
      }
    })(file)

    reader.readAsDataURL(file)
  })

  return promise
}

/**
 * 下载方法
 * @param response
 * @param name 文件名字 非必传
 */
export const downloadFile = (response, name) => {
  const res = response.data
  const type = res.type
  if (type == 'application/json') {
    let fileReader = new FileReader()
    fileReader.readAsText(res)
    fileReader.onload = function (result) {
      let jsondata = JSON.parse(result.target.result)
      message.warning(jsondata.message)
    }
    return
  } else {
    let disposition = response.headers['content-disposition']
    let fileName = getFileNameFromDisposition(disposition)

    let blob = new Blob([res])
    let link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = fileName
    link.click()
    window.URL.revokeObjectURL(link.href)
  }

  function getFileNameFromDisposition(disposition) {
    let fileName = name || '下载文件.zip'
    if (disposition) {
      let respcds = disposition.split(';')
      for (let i = 0; i < respcds.length; i++) {
        let header = respcds[i]
        if (header !== null && header !== '') {
          let headerValue = header.split('=')
          if (headerValue !== null && headerValue.length > 0) {
            if (headerValue[0].trim().toLowerCase() === 'filename') {
              // fileName = decodeURIComponent(header.trim().slice(9))
              fileName = decodeURIComponent(headerValue[1])
              break
            }
          }
        }
      }
    }
    //处理引号
    if (
      (fileName.startsWith("'") || fileName.startsWith('"')) &&
      (fileName.endsWith("'") || fileName.endsWith('"'))
    ) {
      fileName = fileName.substring(1, fileName.length - 1)
    }

    return fileName
  }
}
